﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Drawing;
using System.Xml;
using Google.Documents;
using Google.GData.Documents;
using Google.GData.Extensions;
using Google.GData.Client;
using Google.GData;
using Google.GData.AccessControl;

namespace Astro.Core
{
    public class GoogleDocument
    {
        private String googleAuthToken = null;
        private String user = null;
        private String userOnFirst = null;
        private DocumentsService documentService = new DocumentsService("AstroCMS");
        private DocumentsFeed documentFeed = null;

        public GoogleDocument()
        {
            Instance(SiteSettings.Get().GoogleUser, SiteSettings.Get().GooglePassword);
        }

        public GoogleDocument(string userName, string password)
        {
            Instance(userName, password);
        }

        void Instance(string userName, string password)
        {
            if (this.googleAuthToken == null)
            {
                GoogleClientLogin loginDialog = new GoogleClientLogin(documentService, userName, password);

                loginDialog.Login();
                this.googleAuthToken = loginDialog.AuthenticationToken;
                this.user = loginDialog.User;
                this.userOnFirst = this.user.Split('@')[0];

                if (this.googleAuthToken != null)
                {
                    documentService.SetAuthenticationToken(loginDialog.AuthenticationToken);
                }
            }
        }

        public void CreateFolder(string folderName)
        {
            RequestSettings settings = new RequestSettings("TelligentCMS");
            DocumentsRequest request = new DocumentsRequest(settings);
            request.Service = documentService;
            Feed<Document> feed = request.GetEverything();

            foreach (Document doc in feed.Entries)
            {
                string a = doc.ResourceId;
                string t = doc.Title;
                int i = 1;
            }
        }

        public string UploadFile(Stream data, string contentType, string resourceId, string fileName)
        {
            string feed = string.Format(DocumentsListQuery.foldersUriTemplate, resourceId);
            Uri uri = new Uri(feed);
            AtomEntry entry = documentService.Insert(uri, data, contentType, fileName);

            return entry.AlternateUri.Content;
        }
    }
}